package com.tocici.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.DateUtil;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.DateUtils;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import com.tocici.domain.bo.UserUseTimeBo;
import com.tocici.domain.vo.UserUseTimeVo;
import com.tocici.domain.UserUseTime;
import com.tocici.mapper.UserUseTimeMapper;
import com.tocici.service.IUserUseTimeService;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 用户听歌时段Service业务层处理
 *
 * @author zeraul
 * @date 2025-03-04
 */
@RequiredArgsConstructor
@Service
public class UserUseTimeServiceImpl implements IUserUseTimeService {

    private final UserUseTimeMapper baseMapper;

    private final StringRedisTemplate redisTemplate;

    /**
     * 查询用户听歌时段
     *
     * @param timeId 主键
     * @return 用户听歌时段
     */
    @Override
    public UserUseTimeVo queryById(Long timeId){
        return baseMapper.selectVoById(timeId);
    }

    /**
     * 分页查询用户听歌时段列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 用户听歌时段分页列表
     */
    @Override
    public TableDataInfo<UserUseTimeVo> queryPageList(UserUseTimeBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<UserUseTime> lqw = buildQueryWrapper(bo);
        Page<UserUseTimeVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的用户听歌时段列表
     *
     * @param bo 查询条件
     * @return 用户听歌时段列表
     */
    @Override
    public List<UserUseTimeVo> queryList(UserUseTimeBo bo) {
        LambdaQueryWrapper<UserUseTime> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<UserUseTime> buildQueryWrapper(UserUseTimeBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<UserUseTime> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getTimeId() != null, UserUseTime::getTimeId, bo.getTimeId());
        lqw.eq(bo.getUserId() != null, UserUseTime::getUserId, bo.getUserId());
        lqw.eq(bo.getHour() != null, UserUseTime::getHour, bo.getHour());
        lqw.eq(bo.getIsDeleted() != null, UserUseTime::getIsDeleted, bo.getIsDeleted());
        return lqw;
    }

    /**
     * 新增用户听歌时段
     *
     * @param bo 用户听歌时段
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(UserUseTimeBo bo){
        UserUseTime add = MapstructUtils.convert(bo, UserUseTime.class);
        validEntityBeforeSave(add);
        String[] split = DateUtils.getTimeWithHourMinuteSecond().split(":");
        Integer hours = Integer.valueOf(split[0]);
        add.setHour(hours);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setTimeId(add.getTimeId());
        }
        redisTemplate.opsForValue().set("flag:"+bo.getUserId().toString(),String.valueOf(false),60, TimeUnit.MINUTES);
        return flag;
    }

    /**
     * 修改用户听歌时段
     *
     * @param bo 用户听歌时段
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(UserUseTimeBo bo) {
        UserUseTime update = MapstructUtils.convert(bo, UserUseTime.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(UserUseTime entity) {
        // 新增数据前，先要检查redis的flag是否开启，flag的作用是分割时间段，每个用户在同一时间段只有一条记录
        String result = redisTemplate.opsForValue().get("flag:" + entity.getUserId().toString());
        if (result == null){
            return;

        }
        if (String.valueOf(false).equals(result)){
            throw new ServiceException("已存在记录");
        }


    }

    /**
     * 校验并批量删除用户听歌时段信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public List<Integer> getUsedTime(Date start, Date end) {
        ArrayList<Integer> integers = new ArrayList<>();

        for (int i = 0; i < 24; i++) {
            LambdaQueryWrapper<UserUseTime> lqw = new LambdaQueryWrapper<>();
            lqw.eq(UserUseTime::getHour,i);
            lqw.between(UserUseTime::getCreateTime,start,end);
            Long l = this.baseMapper.selectCount(lqw);
            integers.add(l.intValue());
        }
        return integers;
    }

    @Async("threadPoolTaskExecutor")
    @Scheduled(cron = "0 0 * * * *")
    public void initTimer(){
        Set<String> keys = redisTemplate.keys("flag:" + "*");
        HashMap<String, String> map = new HashMap<>();
        keys.forEach(key -> {
            map.put(key,String.valueOf(true));
        });
        redisTemplate.opsForValue().multiSet(map);
    }
}
